package com.bjpowernode.config.handler;

import com.bjpowernode.result.R;
import com.bjpowernode.util.JSONUtil;
import com.bjpowernode.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 没有权限访问的handler
 *
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //返回json

        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        //设置响应内容类型(媒体类型)
        response.setContentType("application/json;charset=utf-8");

        //返回JSON出去
        R result = new R(403,"权限不足，请联系系统管理员授权", null);

        //把result对象转成JSON
        String json = JSONUtil.toJSON(result);

        //结果写出去
        ResponseUtil.write(response, json);
    }
}
